package com.cyf.merchat.service.impl;

import com.alibaba.fastjson.JSON;
import com.cyf.activemq.network.bean.MqBusinessOpt;
import com.cyf.activemq.network.bean.MqSendCouponReq;
import com.cyf.activemq.service.SendMsgService;
import com.cyf.app.network.bean.AppBusinessRsp;
import com.cyf.app.service.AppPushService;
import com.cyf.db.bean.*;
import com.cyf.db.mapper.*;
import com.cyf.merchat.network.bean.*;
import com.cyf.merchat.service.MerchantService;
import com.cyf.service.AppUserCarService;
import com.cyf.service.bean.CustomException;
import com.cyf.util.*;
import com.cyf.web.network.bean.WebBusinessRsp;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商户操作业务接口实现类
 * Created by cage on 2017/3/29.
 */
@Service
public class MerchantServiceImpl implements MerchantService {

    private static final Logger logger = LoggerFactory.getLogger(MerchantServiceImpl.class);
    @Autowired
    private ParkingMapper parkingMapper;
    @Autowired
    private MerchantInfoMapper merchantInfoMapper;
    @Autowired
    private MerchantCouponMapper merchantCouponMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FeeGroupMapper feeGroupMapper;
    @Autowired
    private LocalAdminparaMapper localAdminparaMapper;
    @Autowired
    private AppPushService appPushService;
    @Autowired
    private SendMsgService sendMsgService;
    @Autowired
    private AppUserCarService appUserCarService;
    @Resource
    private RegSmsMapper regSmsMapper;

    @Override
    public MerchantLoginRsp login(MerchantLoginReq req) {
        MerchantLoginRsp rsp = new MerchantLoginRsp();
        rsp.setResult(MerchantBusinessRsp.FAIL);
        try {
            //当商户生成固定二维码时使用
            MerchantInfo merchantInfoByUUid = merchantInfoMapper.getByUUid(req.getUuid());
            if (merchantInfoByUUid != null) {
                req.setLoginName(merchantInfoByUUid.getLoginName());
                req.setLoginPwd(merchantInfoByUUid.getPassWord());
            }

            List<MerchantInfo> infoList = merchantInfoMapper.getByNameAndPwd(req.getLoginName(), req.getLoginPwd());
            if (infoList == null || infoList.size() == 0) {
                rsp.setStrError("用户名或密码错误！");
                return rsp;
            }
            List<MerchantInfo> merchantInfos = merchantInfoMapper.getByName(req.getLoginName(),
                    merchantInfoByUUid != null ? merchantInfoByUUid.getParkingId() : -1);
            //获取用户登录状态
             ArrayList<MerchantLoginItem> list = new ArrayList<>();
            for (MerchantInfo merchantInfo : merchantInfos) {
                Parking parking = parkingMapper.getParkingById(merchantInfo.getParkingId());
                LocalAdminpara localAdminpara = localAdminparaMapper.getByParkingIdAndParaKey(merchantInfo.getParkingId(),
                        LocalAdminpara.USE_COUPON);
                //获取优惠券绑定的计费规则
                FeeGroup feeGroup = feeGroupMapper.getByLocalFeegroupIdAndParkingId(merchantInfo.getFeeGroupId(), parking.getId());
                if (feeGroup == null) {
                    rsp.setStrError("查找商户的计费规则失败！");
                    return rsp;
                }
                if (StringUtils.isNotEmpty(req.getUuid()) && feeGroup.getUseWay() == 2) {
                    if (StringUtils.isEmpty(merchantInfo.getFeeGroupIdTwo())) {
                        rsp.setStrError("商户未配置线下优惠券，不能发送优惠券,请联系管理员！");
                        return rsp;
                    }
                    String[] feegroupIds = merchantInfo.getFeeGroupIdTwo().split(",");
                    for (String feegroupId : feegroupIds) {
                        feeGroup = feeGroupMapper.getByLocalFeegroupIdAndParkingId(Integer.parseInt(feegroupId), parking.getId());
                        if (feeGroup == null) {
                            rsp.setStrError("查找商户线下优惠券计费规则失败,请联系管理员从新配置！");
                            return rsp;
                        }
                        if (feeGroup.getUseWay() != 2) {
                            break;
                        }
                    }
                }

                if (StringUtils.isNotEmpty(req.getUuid()) && feeGroup.getUseWay() == 2) {
                    rsp.setStrError("商户未配置线下优惠券，不能发送优惠券,请联系管理员！");
                    return rsp;
                }

                if (parking != null && localAdminpara != null && StringUtils.isNotEmpty(localAdminpara.getParaValue())
                        && Integer.parseInt(localAdminpara.getParaValue()) == Parking.ENABLE_COUPON) {
                    MerchantLoginItem item = new MerchantLoginItem();
                    item.setParkingId(parking.getId());
                    item.setParkingName(parking.getName());
                    item.setMerchantId(merchantInfo.getId());
                    item.setLocalMerchantId(merchantInfo.getLocalMerchantInfoId());
                    if (feeGroup.getFreeHours() != null) {
                        item.setFreeHours(feeGroup.getFreeHours());
                    }
                    if (feeGroup.getFreeAmount() != null) {
                        item.setFreeAmount(feeGroup.getFreeAmount());
                    }
                    if (merchantInfo.getMerchantType() != null
                            && merchantInfo.getMerchantType() == MerchantInfo.MERCHANT_TYPE_ALL_COUPON_TIME) {
                        item.setRemainAllHours(merchantInfo.getRemainAllHours());
                    } else {
                        item.setRemainAllHours(0);
                    }

                    if (merchantInfo.getMerchantType() != null && merchantInfo.getMerchantType() == MerchantInfo.MERCHANT_TYPE_ALL_COUPON_AMOUNT) {
                        item.setBalance(merchantInfo.getBalance());
                    } else {
                        item.setBalance(0);
                    }
                    item.setMerchantType(merchantInfo.getMerchantType() == null ? 1 : merchantInfo.getMerchantType());
                    item.setMerchantFeegroupType(feeGroup.getUseWay() == 2 ? MerchantLoginItem.ONLINE_COUPONS : MerchantLoginItem.OFFLINE_COUPONS);
                    item.setFeeGroupId(feeGroup.getLocalFeegroupId());
                    item.setStallName(merchantInfo.getStallName());
                    list.add(item);
                }
                //merchantInfoMapper.updateMerchantInfoLoginState(merchantInfo.getId(),MerchantInfo.LOGIN);
            }

            rsp.setItems(list);
            rsp.setResult(MerchantBusinessRsp.SUCCESS);
        } catch (Exception e) {
            logger.error("商户登录异常：{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    public MerchantLoginRsp appLogin(MerchantLoginReq req) {
        MerchantLoginRsp rsp = new MerchantLoginRsp();
        rsp.setResult(MerchantBusinessRsp.FAIL);
        try {
            //当商户生成固定二维码时使用
            MerchantInfo merchantInfoByUUid = merchantInfoMapper.getByUUid(req.getUuid());
            if (merchantInfoByUUid != null) {
                req.setLoginName(merchantInfoByUUid.getLoginName());
                req.setLoginPwd(merchantInfoByUUid.getPassWord());
            }
            RegSms rsgSms = regSmsMapper.getByMobile(req.getLoginName());
            if (rsgSms == null) {
                rsp.setStrError("验证码已超时");
                return rsp;
            }
            if (!rsgSms.getCode().equals(req.getCode())) {
                rsp.setStrError("验证码不正确");
                return rsp;
            }
            List<MerchantInfo> merchantInfos = merchantInfoMapper.getByName(req.getLoginName(), -1);
            if (merchantInfos == null || merchantInfos.size() == 0) {
                rsp.setStrError("未注册商户信息！");
                return rsp;
            }
            ArrayList<MerchantLoginItem> list = new ArrayList<>();
            for (MerchantInfo merchantInfo : merchantInfos) {
                /*if(merchantInfo.getLoginState()!=null&&merchantInfo.getLoginState()==1){
                    rsp.setStrError("账号已经登录不能重复登录！");
                    return rsp;
                }*/
                Parking parking = parkingMapper.getParkingById(merchantInfo.getParkingId());
                LocalAdminpara localAdminpara = localAdminparaMapper.getByParkingIdAndParaKey(merchantInfo.getParkingId(),
                        LocalAdminpara.USE_COUPON);
                //获取优惠券绑定的计费规则
                FeeGroup feeGroup = feeGroupMapper.getByLocalFeegroupIdAndParkingId(merchantInfo.getFeeGroupId(), parking.getId());
                if (feeGroup == null) {
                    rsp.setStrError("查找商户的计费规则失败！");
                    return rsp;
                }
                if (parking != null && localAdminpara != null && StringUtils.isNotEmpty(localAdminpara.getParaValue())
                        && Integer.parseInt(localAdminpara.getParaValue()) == Parking.ENABLE_COUPON) {
                    MerchantLoginItem item = new MerchantLoginItem();
                    item.setParkingId(parking.getId());
                    item.setParkingName(parking.getName());
                    item.setMerchantId(merchantInfo.getId());
                    item.setLocalMerchantId(merchantInfo.getLocalMerchantInfoId());
                    if (feeGroup.getFreeHours() != null) {
                        item.setFreeHours(feeGroup.getFreeHours());
                    }
                    if (feeGroup.getFreeAmount() != null) {
                        item.setFreeAmount(feeGroup.getFreeAmount());
                    }
                    if (merchantInfo.getMerchantType() != null
                            && merchantInfo.getMerchantType() == MerchantInfo.MERCHANT_TYPE_ALL_COUPON_TIME) {
                        item.setRemainAllHours(merchantInfo.getRemainAllHours());
                    } else {
                        item.setRemainAllHours(0);
                    }

                    if (merchantInfo.getMerchantType() != null && merchantInfo.getMerchantType() == MerchantInfo.MERCHANT_TYPE_ALL_COUPON_AMOUNT) {
                        item.setBalance(merchantInfo.getBalance());
                    } else {
                        item.setBalance(0);
                    }
                    item.setMerchantType(merchantInfo.getMerchantType() == null ? 1 : merchantInfo.getMerchantType());
                    item.setMerchantFeegroupType(feeGroup.getUseWay() == 2 ? MerchantLoginItem.ONLINE_COUPONS : MerchantLoginItem.OFFLINE_COUPONS);
                    list.add(item);
                }
                //merchantInfoMapper.updateMerchantInfoLoginState(merchantInfo.getId(),MerchantInfo.LOGIN);
            }
            regSmsMapper.deleteByMobile(req.getLoginName());
            rsp.setItems(list);
            rsp.setResult(MerchantBusinessRsp.SUCCESS);
        } catch (Exception e) {
            logger.error("商户登录异常：{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    public MerchantLoginRsp signOutLogin(Integer merchantId) {
        MerchantLoginRsp rsp = new MerchantLoginRsp();
        rsp.setResult(MerchantBusinessRsp.SUCCESS);
        rsp.setStrError("退出成功");
        try {
            //根据商户id获取商户手机号
            MerchantInfo info = merchantInfoMapper.getById(merchantId);
            if (info != null) {
                List<MerchantInfo> merchantInfos = merchantInfoMapper.getByName(info.getLoginName(), -1);
                for (MerchantInfo m : merchantInfos) {
                    if (m != null) {
                        merchantInfoMapper.updateMerchantInfoLoginState(m.getId(), MerchantInfo.NOTLOGIN);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rsp;
    }

    @Override
    public MerchantLoginRsp switchParking(Integer merchantId) {
        MerchantLoginRsp rsp = new MerchantLoginRsp();
        rsp.setResult(MerchantBusinessRsp.FAIL);
        try {
            MerchantInfo merchantInfo = merchantInfoMapper.getById(merchantId);
            ArrayList<MerchantLoginItem> list = new ArrayList<>();
            Parking parking = parkingMapper.getParkingById(merchantInfo.getParkingId());
            LocalAdminpara localAdminpara = localAdminparaMapper.getByParkingIdAndParaKey(merchantInfo.getParkingId(),
                    LocalAdminpara.USE_COUPON);
            //获取优惠券绑定的计费规则
            FeeGroup feeGroup = feeGroupMapper.getByLocalFeegroupIdAndParkingId(merchantInfo.getFeeGroupId(), parking.getId());
            if (feeGroup == null) {
                rsp.setStrError("查找商户的计费规则失败！");
                return rsp;
            }
            if (parking != null && localAdminpara != null && StringUtils.isNotEmpty(localAdminpara.getParaValue())
                    && Integer.parseInt(localAdminpara.getParaValue()) == Parking.ENABLE_COUPON) {
                MerchantLoginItem item = new MerchantLoginItem();
                item.setParkingId(parking.getId());
                item.setParkingName(parking.getName());
                item.setMerchantId(merchantInfo.getId());
                item.setLocalMerchantId(merchantInfo.getLocalMerchantInfoId());
                if (feeGroup.getFreeHours() != null) {
                    item.setFreeHours(feeGroup.getFreeHours());
                }
                if (feeGroup.getFreeAmount() != null) {
                    item.setFreeAmount(feeGroup.getFreeAmount());
                }
                if (merchantInfo.getMerchantType() != null
                        && merchantInfo.getMerchantType() == MerchantInfo.MERCHANT_TYPE_ALL_COUPON_TIME) {
                    item.setRemainAllHours(merchantInfo.getRemainAllHours());
                } else {
                    item.setRemainAllHours(0);
                }

                if (merchantInfo.getMerchantType() != null && merchantInfo.getMerchantType() == MerchantInfo.MERCHANT_TYPE_ALL_COUPON_AMOUNT) {
                    item.setBalance(merchantInfo.getBalance());
                } else {
                    item.setBalance(0);
                }
                item.setMerchantType(merchantInfo.getMerchantType() == null ? 1 : merchantInfo.getMerchantType());
                item.setMerchantFeegroupType(feeGroup.getUseWay() == 2 ? MerchantLoginItem.ONLINE_COUPONS : MerchantLoginItem.OFFLINE_COUPONS);
                item.setStallName(merchantInfo.getStallName());
                list.add(item);
                rsp.setItem(item);
            }
            rsp.setItems(list);
            rsp.setResult(MerchantBusinessRsp.SUCCESS);
        } catch (Exception e) {
            rsp.setStrError("切换车场错误");
        }
        return rsp;
    }

    @Override
    public MerchantCheckAppUserByMobileRsp checkIsAppUserByMobile(MerchantCheckAppUserByMobileReq req) {
        MerchantCheckAppUserByMobileRsp rsp = new MerchantCheckAppUserByMobileRsp();
        rsp.setResult(WebBusinessRsp.FAIL);
        try {
            Parking parking = parkingMapper.getParkingById(req.getParkingId());
            if (parking == null) {
                rsp.setStrError("车场不存在，查询信息失败！");
                return rsp;
            }
            User user = userMapper.getByMobile(req.getMobile());
            if (user == null) { // 手机号未注册微信公众号、app、adps
                user = new User();
                user.setMobile(req.getMobile());
                user.setCreatedTime(new Date());
                user.setToken(UUID.randomUUID().toString().replace("-", ""));
                userMapper.insertUser(user);
            } else if (StringUtils.isEmpty(user.getToken())) {   // 手机号注册了微信公众号或adps，但没有注册app
                user.setToken(UUID.randomUUID().toString().replace("-", ""));
                userMapper.updateAppInfo(user);
            }
            rsp.setResult(WebBusinessRsp.SUCCESS);
            rsp.setSubResult(MerchantCheckAppUserByMobileRsp.ISAPPUSER);
        } catch (Exception e) {
            rsp.setStrError("服务器异常！");
            logger.error("nps网站根据手机号检查是否是app用户异常：{}", e);
        }
        return rsp;
    }

    @Override
    public MerchantSaveCouponInfoRsp saveCouponInfo(MerchantSaveCouponInfoReq req) {
        MerchantSaveCouponInfoRsp rsp = new MerchantSaveCouponInfoRsp();
        rsp.setResult(MerchantBusinessRsp.FAIL);
        try {
            logger.info("请求参数：{}", req.toString());
            if (req.getPlate() == null || req.getPlate().length() < 7) {
                rsp.setStrError("车牌号错误！");
                return rsp;
            }
            // 校验信息
            Parking parking = parkingMapper.getParkingById(req.getParkingId());
            if (parking == null) {
                rsp.setStrError("车场不存在！");
                return rsp;
            }
            LocalAdminpara localAdminpara = localAdminparaMapper.getByParkingIdAndParaKey(parking.getId(),
                    LocalAdminpara.USE_COUPON);
            if (localAdminpara == null || StringUtils.isEmpty(localAdminpara.getParaValue())
                    || Integer.parseInt(localAdminpara.getParaValue()) != Parking.ENABLE_COUPON) {
                rsp.setStrError("该车场不支持优惠券！");
                return rsp;
            }
            MerchantInfo merchantInfo = merchantInfoMapper.getById(req.getMerchantId());
            if (merchantInfo == null) {
                rsp.setStrError("该商户不存在！");
                return rsp;
            }
            if (merchantInfo.getStatus() == MerchantInfo.DISABLE) {
                rsp.setStrError("该商户已被禁用！");
                return rsp;
            }

            if (merchantInfo.getMerchantType() == null || merchantInfo.getMerchantType() == MerchantInfo.MERCHANT_TYPE_TIME_SLOT) {
                if (merchantInfo.getMaxCouponCount() == null || merchantInfo.getHours() == null) {
                    rsp.setStrError("商户信息不完善！");
                    return rsp;
                }
                Date date = DateUtil.getDateAfterSeconds(new Date(), merchantInfo.getHours() * (-3600));
                Integer count = merchantCouponMapper.getCountByMerchantIdAndDate(merchantInfo.getId(), date);
                if (count != null && count >= merchantInfo.getMaxCouponCount()) {
                    rsp.setResult(MerchantSaveCouponInfoRsp.RESULT_COUPON_MAX);
                    rsp.setStrError("优惠券生成数量已达上限！");
                    return rsp;
                }
            } else if (merchantInfo.getMerchantType() == null || merchantInfo.getMerchantType() == MerchantInfo.MERCHANT_TYPE_ALL_COUPON_TIME) {
                if (merchantInfo.getRemainAllHours() <= 0) {
                    rsp.setResult(MerchantSaveCouponInfoRsp.RESULT_COUPON_MAX);
                    rsp.setStrError("剩余小时不足，请联系管理员充值！");
                    return rsp;
                }
            } else {
                //优惠金额
                if (merchantInfo.getBalance() <= 0) {
                    rsp.setResult(MerchantSaveCouponInfoRsp.RESULT_COUPON_MAX);
                    rsp.setStrError("剩余金额不足，请联系管理员充值！");
                    return rsp;
                }
            }
            FeeGroup merchantFeeGroup = feeGroupMapper.getByLocalFeegroupIdAndParkingId(req.getFeegroupId() == 0 ?
                    merchantInfo.getFeeGroupId() : req.getFeegroupId(), parking.getId());
            if (merchantFeeGroup == null || merchantFeeGroup.getValid() == null) {
                rsp.setStrError("查找商户的优惠券计费规则失败！");
                return rsp;
            }
            FeeGroup feeGroup = feeGroupMapper.getByLocalFeegroupIdAndParkingId(merchantFeeGroup.getBindingFeeGroupId(), parking.getId());
            if (feeGroup == null) {
                rsp.setStrError("查找商户的计费规则失败！");
                return rsp;
            }
            User user = userMapper.getByMobile(req.getMobile());
            if (user == null) {
                rsp.setStrError("该手机号未注册app！");
                return rsp;
            }

            if (merchantFeeGroup.getQrCodeType() != FeeGroup.COUPON_TYPE_CHANGE_FEEGROUP) { // 优惠券类型不是切换计费规则
                // 生成优惠券，给app用户添加该辆车
                AppCar car = new AppCar();
                car.setPlate(req.getPlate().toUpperCase());
                appUserCarService.addCar(user, car);
            }

            //此处限制当该车辆有未使用的优惠券时，不能在次发放
//            int countByPlate = merchantCouponMapper.getCountByPlate(req.getPlate(), req.getParkingId());
//            if (countByPlate > 0) {
//                rsp.setStrError(req.getPlate() + "有未使用的优惠券!");
//                return rsp;
//            }

            // 保存优惠券信息到数据库
            MerchantCoupon merchantCoupon = new MerchantCoupon();
            merchantCoupon.setMerchantId(merchantInfo.getId());
            merchantCoupon.setParkingId(parking.getId());
            merchantCoupon.setMobile(user.getMobile());
            merchantCoupon.setAppUserId(user.getId());
            merchantCoupon.setPlate(req.getPlate().trim().toUpperCase());
            Date createdTime = new Date();
            Date endTime = DateUtil.getDateAfterSeconds(createdTime, merchantFeeGroup.getValid());
            merchantCoupon.setCreatedTime(createdTime);
            merchantCoupon.setEndTime(endTime);
            merchantCoupon.setStatus(MerchantCoupon.UNUSED);
            merchantCoupon.setSendToParking(MerchantCoupon.SEND_FAIL);
            merchantCoupon.setCouponCode(merchantCoupon.generateCouponCode());
            merchantCoupon.setCouponType(merchantFeeGroup.getQrCodeType());
            if (req.getMerchantFeegroupType() == 1) {
                //线上优惠券

            }
            if (merchantFeeGroup.getQrCodeType() == FeeGroup.COUPON_TYPE_HOURS) {
                if (req.getTime() > 0) {
                    merchantCoupon.setFreeHours(req.getTime());
                } else {
                    merchantCoupon.setFreeHours(merchantFeeGroup.getFreeHours());
                }
            } else {
                merchantCoupon.setFreeAmount(merchantFeeGroup.getFreeAmount());
            }
            merchantCoupon.setFeeGroupId(merchantFeeGroup.getId());
            merchantCoupon.setBindingFeeGroupId(feeGroup.getId());

            merchantCoupon.setFreeLimit(merchantFeeGroup.getFreeLimit());
            merchantCoupon.setLimitParkingId(merchantFeeGroup.getParkingId());
            merchantCoupon.setUseWay(merchantFeeGroup.getUseWay());
            merchantCoupon.setType(1);
            merchantCoupon.setDiscount(merchantFeeGroup.getDiscount());
            merchantCoupon.setLocalParkingId(merchantInfo.getLocalParkingId());
            merchantCouponMapper.insertMerchantCoupon(merchantCoupon);
            rsp.setResult(MerchantBusinessRsp.SUCCESS);
            rsp.setItem(getMerchantInfo(merchantInfoMapper.getById(req.getMerchantId())));

            // 1、向app发送通知
            appPushService.pushCouponNotification(user.getMobile());

            if (parking.getParkingType() == Parking.PARKING_TYPE_ROADSIDE) {    // 路侧停车，直接更新优惠券状态
                merchantCouponMapper.updateSendParkingStatus(merchantCoupon.getId(), merchantCoupon.getId(), 1);
            } else {
                // 2、向TOC发送信息
                MqSendCouponReq mqSendCouponReq = new MqSendCouponReq();
                BeanUtils.copyProperties(merchantCoupon, mqSendCouponReq);

                String uuid = UUID.randomUUID().toString();
                mqSendCouponReq.setUuid(uuid);
                mqSendCouponReq.setOptid(MqBusinessOpt.SENDCOUPON);
                mqSendCouponReq.setParkingId(parking.getId());
                mqSendCouponReq.setLocalMerchantId(merchantInfo.getLocalMerchantInfoId());
                mqSendCouponReq.setMerchantCouponId(merchantCoupon.getId());

                mqSendCouponReq.setCreatedTime(DateUtil.convertDate2Seconds(createdTime));
                mqSendCouponReq.setEndTime(DateUtil.convertDate2Seconds(endTime));

                mqSendCouponReq.setLocalFeeGroupId(merchantFeeGroup.getLocalFeegroupId());
                mqSendCouponReq.setLocalBindingFeeGroupId(feeGroup.getLocalFeegroupId());

                sendMsgService.sendQueueMessageText(ObjectMapperUtils.getObjectMapper().writeValueAsString(mqSendCouponReq));
            }

        } catch (CustomException e) {
            rsp.setStrError(e.getMessage());
        } catch (Exception e) {
            logger.error("商户异常：{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    public MerchantUpdatePwdRsp updatePwdRsp(MerchantUpdatePwdReq req) {
        MerchantUpdatePwdRsp rsp = new MerchantUpdatePwdRsp();
        rsp.setResult(MerchantBusinessRsp.FAIL);
        try {
            // 校验信息
            List<Integer> merchantIdList = merchantInfoMapper.getPassWord(req.getLoginName(), req.getOldPassWord());
            if (merchantIdList.size() > 0) {
                MerchantInfo merchantInfo = new MerchantInfo();
                merchantInfo.setPassWord(MD5.getEncode(req.getNewPassWord()));
                for (Integer id : merchantIdList) {
                    merchantInfoMapper.upatePwd(id, MD5.getEncode(req.getNewPassWord()));
                }
                rsp.setResult(MerchantBusinessRsp.SUCCESS);
                rsp.setStrError("密码修改成功!");
            } else {
                rsp.setStrError("旧密码不正确!");
            }
        } catch (Exception e) {
            logger.error("商户修改密码异常！：{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    public MerchantCouponLssueRecordRsp issueRecord(MerchantCouponLssueRecordReq req) {
        MerchantCouponLssueRecordRsp rsp = new MerchantCouponLssueRecordRsp();
        rsp.setResult(MerchantBusinessRsp.FAIL);
        try {
            String date = null;//DateUtil.formatDate(new Date(), "yyyy-MM-dd");
            req.setEndTime(date);
            //统计商户发放的优惠券个数
            int countTotle = merchantCouponMapper.getCountCoupon(req.getParkingId(), req.getMerchantId(), req.getEndTime(), -1);
            //统计商户已使用的优惠券个数
            int countUse = merchantCouponMapper.getCountCoupon(req.getParkingId(), req.getMerchantId(), req.getEndTime(), 0);
            //查询已发放优惠券列表
            PageHelper.startPage(req.getPage(), req.getPageSize());
            List<MerchantCoupon> countByMerchantIdAndParkingId =
                    merchantCouponMapper.getCountByMerchantIdAndParkingId(req.getParkingId(),
                            req.getMerchantId(), req.getStatus(), req.getCreatedTime(), req.getEndTime());
            List<MerchantCouponVo> list = new ArrayList();
            for (MerchantCoupon merchantCoupon : countByMerchantIdAndParkingId) {
                MerchantCouponVo merchantCouponVo = new MerchantCouponVo();
                if (merchantCoupon.getActualFee() == null) {
                    merchantCoupon.setActualFee(0);
                }
                if (merchantCoupon.getCouponFee() == null) {
                    merchantCoupon.setCouponFee(0);
                }
                if (merchantCoupon.getActualFee() == 0 && merchantCoupon.getCouponFee() == 0) {
                    merchantCoupon.setShouldFee(0);
                }
                merchantCouponVo.setActualFee(merchantCoupon.getActualFee());
                merchantCouponVo.setShouldFee(merchantCoupon.getShouldFee());
                merchantCouponVo.setCouponFee(merchantCoupon.getCouponFee());
                merchantCouponVo.setPlate(merchantCoupon.getPlate());
                merchantCouponVo.setId(merchantCoupon.getId());
                merchantCouponVo.setStatus(merchantCoupon.getStatus());
                merchantCouponVo.setCreatedTime(DateUtil.formatDate(merchantCoupon.getCreatedTime(), "yyyy-MM-dd HH:mm:ss"));
                if(merchantCoupon.getTimespent()!= null){
                    merchantCouponVo.setTimespent(DateUtil.formatDate(merchantCoupon.getTimespent(), "yyyy-MM-dd HH:mm:ss"));
                }
                if (merchantCoupon.getCouponType() != null) {
                    merchantCouponVo.setCouponType(merchantCoupon.getCouponType());
                }
                merchantCouponVo.setDiscount(merchantCoupon.getDiscount());
                if (merchantCoupon.getFreeAmount() != null) {
                    merchantCouponVo.setFreeAmount(merchantCoupon.getFreeAmount());
                }
                if (merchantCoupon.getFreeHours() != null) {
                    merchantCouponVo.setFreeHours(merchantCoupon.getFreeHours());
                }
                merchantCouponVo.setUseWay(merchantCoupon.getUseWay());
                if (StringUtils.isNotEmpty(merchantCoupon.getCarName())) {
                    merchantCouponVo.setCarName(merchantCoupon.getCarName());
                }
                if (StringUtils.isNotEmpty(merchantCoupon.getMobile())) {
                    merchantCouponVo.setMobile(merchantCoupon.getMobile());
                }
                merchantCouponVo.setEndTime(DateUtil.formatDate(merchantCoupon.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
                list.add(merchantCouponVo);
            }
            //获取合计
            MerchantCouponVo vo = merchantCouponMapper.selectMerchantCouponTotal(req.getParkingId(),req.getMerchantId());
            rsp.setStatistics(vo);
            rsp.setTotal(new PageInfoBT(countByMerchantIdAndParkingId).getTotal());
            rsp.setCouponTotal(countTotle);
            rsp.setCouponUser(countUse);
            rsp.setCouponList(list);
            rsp.setResult(MerchantBusinessRsp.SUCCESS);
            rsp.setStrError("获取成功!");
        } catch (Exception e) {
            logger.error("商户获取发放记录异常！：{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    public AppBusinessRsp takeBack(String ids) {
        AppBusinessRsp rsp = new AppBusinessRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        String meid = "";
        if (StringUtils.isNotBlank(ids)) {
            String id[] = ids.split(",");
            MerchantCoupon coupon = merchantCouponMapper.getById(Integer.parseInt(id[0]));
            if (coupon != null) {
                for (String str : id) {
                    MerchantCoupon c = merchantCouponMapper.getById(Integer.parseInt(str));
                    if(new Date().getTime()>DateUtil.getTimeTransformation(coupon.getEndTime()).getTime()){
                        rsp.setStrError("优惠券已过期无法回收！");
                        return rsp;
                    }
                }
                MerchantInfo info = merchantInfoMapper.getById(coupon.getMerchantId());
                Integer fee = 0;
                for (String str : id) {
                    MerchantCoupon c = merchantCouponMapper.getById(Integer.parseInt(str));
                    if (info.getMerchantType() == 2) {
                        //优惠时间
                        fee = fee + c.getFreeHours();
                    } else if (info.getMerchantType() == 3) {
                        //优惠金额
                        fee = fee + c.getFreeAmount();
                    }
                    merchantCouponMapper.updateMerchantStatus(Integer.parseInt(str));
                }
                if (info.getMerchantType() == 2) {
                    //优惠时间
                    merchantInfoMapper.updateMerchantInfoFreeHours(info.getId(), info.getRemainAllHours() + (fee / 60));
                } else if (info.getMerchantType() == 3) {
                    //优惠金额
                    merchantInfoMapper.updateMerchantInfoFreeAmount(info.getId(), info.getBalance() + fee);
                }
                rsp.setItem(getMerchantInfo(merchantInfoMapper.getById(info.getId())));
                rsp.setResult(AppBusinessRsp.SUCCESS);
                rsp.setStrError("操作成功");
            }
        } else {
            rsp.setStrError("请选择要回收的优惠券！");
        }
        return rsp;
    }

    @Override
    public MerchantFeegroupRsp parkingFeegroup(Integer parkingId, Integer merchatId) {
        MerchantFeegroupRsp rsp = new MerchantFeegroupRsp();
        try {
            List<FeegroupListRsp> feeGroupList = feeGroupMapper.selectByBillingType(merchatId, parkingId);
            feeGroupList.removeAll(Collections.singleton(null));
            Date createdTime = null;
            MerchantInfo info = merchantInfoMapper.getById(merchatId);
            //根据商户id获取商户信息
            MerchantInfo merchantInfo = merchantInfoMapper.getById(merchatId);
            if (merchantInfo != null && StringUtils.isNotBlank(merchantInfo.getFeeGroupIdTwo())) {
                String feeGroupIds[] = merchantInfo.getFeeGroupIdTwo().split(",");
                for (String id : feeGroupIds) {
                    FeeGroup group = feeGroupMapper.getByLocalFeegroupIdAndParkingId(Integer.parseInt(id), parkingId);
                    if (group != null) {
                        FeegroupListRsp listRsp = new FeegroupListRsp();
                        listRsp.setUseWay(group.getUseWay());
                        listRsp.setQrCodeType(group.getQrCodeType());
                        listRsp.setFeeGroupId(group.getLocalFeegroupId());
                        listRsp.setName(group.getName());
                        listRsp.setValid(group.getValid());
                        feeGroupList.add(listRsp);
                    }
                }
            }
            List<FeegroupListRsp> listRsps = new ArrayList<>();
            for (FeegroupListRsp feegroup : feeGroupList) {
                if (feegroup.getQrCodeType() != null) {
                    if (feegroup.getQrCodeType() == 1 && feegroup.getUseWay() == 2) {

                    } else {
                        listRsps.add(feegroup);
                    }
                }
            }
            for (FeegroupListRsp feegroup : feeGroupList) {
                //计算到期时间
                if (feegroup.getValid() != null) {
                    if (feegroup.getUseWay() == 1) {
                        createdTime = new Date();
                    } else {
                        if (info != null) {
                            createdTime = merchantCouponMapper.selectMerchntRechargeTime(parkingId, info.getLocalMerchantInfoId());
                            if (createdTime == null) {
                                createdTime = new Date();
                            }
                        }
                    }
                    //当前时间改为充值时间
                    Date dateAfterSeconds = DateUtil.getDateAfterSeconds(createdTime, feegroup.getValid());
                    feegroup.setEndTime(DateUtil.formatDate(dateAfterSeconds, "yyyy-MM-dd"));
                }
                if (feegroup.getUseWay() == MerchantCoupon.USEWAY_OFFLINE) {
                    feegroup.setUseWayDesc("线下使用");
                } else if (feegroup.getUseWay() == MerchantCoupon.USEWAY_ONLINE) {
                    feegroup.setUseWayDesc("线上使用");
                }
            }
            rsp.setResult(MerchantBusinessRsp.SUCCESS);
            rsp.setData(listRsps);
        } catch (Exception e) {
            e.printStackTrace();
            rsp.setResult(MerchantBusinessRsp.FAIL);
            rsp.setStrError("获取当前车场的优惠券规则异常！");
        }
        return rsp;
    }

    @Override
    public MerchantFeegroupRsp parkingByFeegroupId(Integer parkingId, Integer feeGroupId) {
        MerchantFeegroupRsp rsp = new MerchantFeegroupRsp();
        try {
            FeegroupListRsp feeGroup = feeGroupMapper.parkingByFeegroupId(parkingId, feeGroupId);
            Date date = new Date();
            //计算到期时间
            if (feeGroup.getValid() != null) {
                Date dateAfterSeconds = DateUtil.getDateAfterSeconds(date, feeGroup.getValid());
                feeGroup.setEndTime(DateUtil.formatDate(dateAfterSeconds, "yyyy-MM-dd"));
            }
            if (feeGroup.getUseWay() == MerchantCoupon.USEWAY_OFFLINE) {
                feeGroup.setUseWayDesc("线下使用");
            } else if (feeGroup.getUseWay() == MerchantCoupon.USEWAY_ONLINE) {
                feeGroup.setUseWayDesc("线上使用");
            }
            rsp.setResult(MerchantBusinessRsp.SUCCESS);
            rsp.setData(feeGroup);
        } catch (Exception e) {
            rsp.setResult(MerchantBusinessRsp.FAIL);
            rsp.setStrError("获取当前车场的优惠券规则异常！");
        }
        return rsp;
    }

    @Override
    public MerchantSaveCouponInfoRsp saveCoupon(SaveCouponReq req) {
        MerchantSaveCouponInfoRsp rsp = new MerchantSaveCouponInfoRsp();
        rsp.setResult(MerchantBusinessRsp.FAIL);
        try {
            logger.info("请求参数：{}", req.toString());
            if (req.getUseWay() == MerchantCoupon.USEWAY_OFFLINE && StringUtils.isEmpty(req.getMobile())) {
                req.setMobile("11111111111");
            }
            // 校验信息
            Parking parking = parkingMapper.getParkingById(req.getParkingId());
            if (parking == null) {
                rsp.setStrError("车场不存在！");
                return rsp;
            }
            LocalAdminpara localAdminpara = localAdminparaMapper.getByParkingIdAndParaKey(parking.getId(),
                    LocalAdminpara.USE_COUPON);
            if (localAdminpara == null || StringUtils.isEmpty(localAdminpara.getParaValue())
                    || Integer.parseInt(localAdminpara.getParaValue()) != Parking.ENABLE_COUPON) {
                rsp.setStrError("该车场不支持优惠券！");
                return rsp;
            }
            MerchantInfo merchantInfo = merchantInfoMapper.getById(req.getMerchantId());
            if (merchantInfo == null) {
                rsp.setStrError("该商户不存在！");
                return rsp;
            }
            if (merchantInfo.getStatus() == MerchantInfo.DISABLE) {
                rsp.setStrError("该商户已被禁用！");
                return rsp;
            }
            FeeGroup merchantFeeGroup = feeGroupMapper.getByLocalFeegroupIdAndParkingId(req.getFeeGroupId(), parking.getId());
            if (merchantFeeGroup == null || merchantFeeGroup.getValid() == null) {
                rsp.setStrError("查找商户的优惠券计费规则失败！");
                return rsp;
            }
            if (merchantInfo.getMerchantType() == null || merchantInfo.getMerchantType() == MerchantInfo.MERCHANT_TYPE_TIME_SLOT) {
                if (merchantInfo.getMaxCouponCount() == null || merchantInfo.getHours() == null) {
                    rsp.setStrError("商户信息不完善！");
                    return rsp;
                }
                Date date = DateUtil.getDateAfterSeconds(new Date(), merchantInfo.getHours() * (-3600));
                Integer count = merchantCouponMapper.getCountByMerchantIdAndDate(merchantInfo.getId(), date);
                if (count != null && count >= merchantInfo.getMaxCouponCount()) {
                    rsp.setResult(MerchantSaveCouponInfoRsp.RESULT_COUPON_MAX);
                    rsp.setStrError("优惠券生成数量已达上限！");
                    return rsp;
                }
            } else if (merchantInfo.getMerchantType() == null || merchantInfo.getMerchantType() == MerchantInfo.MERCHANT_TYPE_ALL_COUPON_TIME) {
                if (merchantInfo.getRemainAllHours() <= 0) {
                    rsp.setResult(MerchantSaveCouponInfoRsp.RESULT_COUPON_MAX);
                    rsp.setStrError("剩余小时不足，请联系管理员充值！");
                    return rsp;
                }else {
                    int issueNumber = req.getIssueNumber();
                    int hourse = (merchantFeeGroup.getFreeHours() * issueNumber)/60;
                    if(hourse>merchantInfo.getRemainAllHours()){
                        rsp.setResult(MerchantSaveCouponInfoRsp.RESULT_COUPON_MAX);
                        rsp.setStrError("剩余小时不足，请联系管理员充值！");
                        return rsp;
                    }
                }

            } else {
                //优惠金额
                if (merchantInfo.getBalance() <= 0) {
                    rsp.setResult(MerchantSaveCouponInfoRsp.RESULT_COUPON_MAX);
                    rsp.setStrError("剩余金额不足，请联系管理员充值！");
                    return rsp;
                }else {
                    int issueNumber = req.getIssueNumber();
                    int blance = merchantFeeGroup.getFreeAmount() * issueNumber;
                    if(blance>merchantInfo.getBalance()){
                        rsp.setResult(MerchantSaveCouponInfoRsp.RESULT_COUPON_MAX);
                        rsp.setStrError("剩余金额不足，请联系管理员充值！");
                        return rsp;
                    }
                }
            }


            FeeGroup feeGroup = feeGroupMapper.getByLocalFeegroupIdAndParkingId(req.getFeeGroupId(), parking.getId());
            if (feeGroup == null) {
                rsp.setStrError("查找商户的计费规则失败！");
                return rsp;
            }
            User user = new User();
            if (req.getUseWay() == MerchantCoupon.USEWAY_ONLINE && StringUtils.isNotEmpty(req.getMobile())) {
                user = userMapper.getByMobile(req.getMobile());
                if (user == null) {
                    rsp.setStrError("该手机号未注册app！");
                    return rsp;
                }
            }

            // 保存优惠券信息到数据库
            List<MerchantCoupon> merchantCouponList = new ArrayList<>();
            Date endTime = null;
            //是否是线下劵，线下劵取值当前时间
            if (feeGroup.getUseWay() == 1) {
                endTime = DateUtil.getDateAfterSeconds(new Date(), merchantFeeGroup.getValid());
            } else {
                //当前时间改为充值时间
                Date createdTime = merchantCouponMapper.selectMerchntRechargeTime(req.getParkingId(), merchantInfo.getLocalMerchantInfoId());
                if (createdTime == null) {
                    createdTime = new Date();
                }else {
                    createdTime =  DateUtil.getTimeTransformation(createdTime);
                }
                endTime = DateUtil.getDateAfterSeconds(createdTime, merchantFeeGroup.getValid());
                if (endTime.getTime() <= new Date().getTime()) {
                    rsp.setStrError("优惠券已过期！");
                    return rsp;
                }
            }
            for (int i = 0; i < req.getIssueNumber(); i++) {
                MerchantCoupon merchantCoupon = new MerchantCoupon();
                merchantCoupon.setCarName(req.getCarName());
                merchantCoupon.setRemark(req.getRemark());
                merchantCoupon.setMerchantId(merchantInfo.getId());
                merchantCoupon.setParkingId(parking.getId());
                merchantCoupon.setMobile(req.getMobile());
                if (req.getUseWay().equals(MerchantCoupon.USEWAY_ONLINE)) {
                    merchantCoupon.setAppUserId(user.getId());
                    merchantCoupon.setCouponCode(merchantCoupon.generateCouponCode());
                } else {
                    merchantCoupon.setAppUserId(0);
                    merchantCoupon.setCouponCode(merchantCoupon.generateCouponCode());
                }
                if (req.getUseWay().equals(MerchantCoupon.USEWAY_OFFLINE)) {
                    merchantCoupon.setPlate(req.getPlate().trim().toUpperCase());
                    merchantCoupon.setCouponCode(merchantCoupon.randCouponCode());
                }
                if (StringUtils.isNotBlank(req.getPlate())) {
                    merchantCoupon.setPlate(req.getPlate().trim().toUpperCase());
                }
                merchantCoupon.setCreatedTime(new Date());
                merchantCoupon.setEndTime(endTime);
                merchantCoupon.setStatus(MerchantCoupon.UNUSED);
                merchantCoupon.setSendToParking(MerchantCoupon.SEND_FAIL);
                merchantCoupon.setCouponType(merchantFeeGroup.getQrCodeType());
                if (merchantFeeGroup.getQrCodeType() == FeeGroup.COUPON_TYPE_HOURS) {
                    merchantCoupon.setFreeHours(merchantFeeGroup.getFreeHours());
                } else {
                    merchantCoupon.setFreeAmount(merchantFeeGroup.getFreeAmount());
                }
                merchantCoupon.setFeeGroupId(merchantFeeGroup.getId());
                merchantCoupon.setBindingFeeGroupId(feeGroup.getId());

                merchantCoupon.setFreeLimit(merchantFeeGroup.getFreeLimit());
                merchantCoupon.setLimitParkingId(merchantFeeGroup.getParkingId());
                merchantCoupon.setUseWay(merchantFeeGroup.getUseWay());
                merchantCoupon.setType(1);
                merchantCoupon.setDiscount(merchantFeeGroup.getDiscount());
                merchantCoupon.setLocalParkingId(merchantInfo.getLocalParkingId());
                merchantCouponList.add(merchantCoupon);
            }
            merchantCouponMapper.insertMerchantCouponList(merchantCouponList);
            List<Integer> couponIds = merchantCouponList.stream().map(p -> p.getId()).collect(Collectors.toList());
            rsp.setCouponIds(couponIds);
            //如果是富茂的车场   就推送优惠券id
            if(req.getParkingId() == 1461){
                String json = JSON.toJSONString(couponIds);
                String result = HttpUtils.postJson("127.0.0.1:8888",json);
                logger.info("向富茂推送生成的优惠券id{}",json);
            }
            //变更优惠券金额
            Integer fee = 0;
            if (merchantFeeGroup.getQrCodeType() == FeeGroup.COUPON_TYPE_HOURS) {
                //小时卷
                fee = merchantInfo.getRemainAllHours() - merchantFeeGroup.getFreeHours() / 60 * req.getIssueNumber();
                merchantInfoMapper.updateMerchantInfoFreeHours(merchantInfo.getId(), fee);
            } else if (merchantFeeGroup.getQrCodeType() == FeeGroup.COUPON_TYPE_AMOUNT) {
                //金额卷
                fee = merchantInfo.getBalance() - merchantFeeGroup.getFreeAmount() * req.getIssueNumber();
                merchantInfoMapper.updateMerchantInfoFreeAmount(merchantInfo.getId(), fee);
            }

            rsp.setResult(MerchantBusinessRsp.SUCCESS);

            if (parking.getParkingType() == Parking.PARKING_TYPE_ROADSIDE) {
                // 路侧停车，直接更新优惠券状态
                for (MerchantCoupon coupon : merchantCouponList) {
                    merchantCouponMapper.updateSendParkingStatus(coupon.getId(), coupon.getId(), 1);
                }
            } else {
                // 2、向TOC发送信息
                for (MerchantCoupon merchantCoupon : merchantCouponList) {
                    MqSendCouponReq mqSendCouponReq = new MqSendCouponReq();
                    BeanUtils.copyProperties(merchantCoupon, mqSendCouponReq);

                    String uuid = UUID.randomUUID().toString();
                    mqSendCouponReq.setUuid(uuid);
                    mqSendCouponReq.setOptid(MqBusinessOpt.SENDCOUPON);
                    mqSendCouponReq.setParkingId(parking.getId());
                    mqSendCouponReq.setLocalMerchantId(merchantInfo.getLocalMerchantInfoId());
                    mqSendCouponReq.setMerchantCouponId(merchantCoupon.getId());

                    mqSendCouponReq.setCreatedTime(DateUtil.convertDate2Seconds(new Date()));
                    mqSendCouponReq.setEndTime(DateUtil.convertDate2Seconds(endTime));

                    mqSendCouponReq.setLocalFeeGroupId(merchantFeeGroup.getLocalFeegroupId());
                    mqSendCouponReq.setLocalBindingFeeGroupId(feeGroup.getLocalFeegroupId());
                    sendMsgService.sendQueueMessageText(ObjectMapperUtils.getObjectMapper().writeValueAsString(mqSendCouponReq));
                }
            }
            rsp.setItem(getMerchantInfo(merchantInfoMapper.getById(req.getMerchantId())));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("商户异常：{}", e.getMessage());
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    public MerchantFeegroupRsp merchantRecharge(Integer parking, Integer merchantId) {
        MerchantFeegroupRsp rsp = new MerchantFeegroupRsp();
        try {
            List<RechargeRecord> rechargerecord = merchantInfoMapper.selectByMerchat(parking, merchantId);
            rsp.setResult(MerchantBusinessRsp.SUCCESS);
            rsp.setData(rechargerecord);
        } catch (Exception e) {
            rsp.setResult(MerchantBusinessRsp.FAIL);
            rsp.setStrError("获取商户充值记录异常");
            logger.error("获取商户充值记录异常{}", e.getMessage());
        }
        return rsp;
    }

    @Override
    public MerchantQrCodeGenerationRsp qrCodeGeneration(Integer merchantId) {
        String QRCODE_URL = "http://wechat.cheyifu2016.com:8080/wexin/login.action?uuid=";
        MerchantQrCodeGenerationRsp merchantQrCodeGenerationRsp = new MerchantQrCodeGenerationRsp();
        merchantQrCodeGenerationRsp.setResult(MerchantBusinessRsp.FAIL);
        try {
            if (merchantId == null) {
                merchantQrCodeGenerationRsp.setStrError("商户Id错误！");
                return merchantQrCodeGenerationRsp;
            }
            MerchantInfo merchantInfo = merchantInfoMapper.getById(merchantId);
            if (merchantInfo == null) {
                merchantQrCodeGenerationRsp.setStrError("未找到商户信息！");
                return merchantQrCodeGenerationRsp;
            }
            if (StringUtils.isEmpty(merchantInfo.getMerchantUUID())) {
                merchantQrCodeGenerationRsp.setStrError("商户不支持生成二维码，请联系管理员更改配置！");
                return merchantQrCodeGenerationRsp;
            }
            merchantQrCodeGenerationRsp.setQrcodeUrl(QRCODE_URL + merchantInfo.getMerchantUUID());
            merchantQrCodeGenerationRsp.setResult(MerchantBusinessRsp.SUCCESS);
        } catch (Exception e) {
            logger.error("商户生成二维码异常！{}", e.getMessage());
            merchantQrCodeGenerationRsp.setStrError("服务器忙，请稍后重试！");
            return merchantQrCodeGenerationRsp;
        }
        return merchantQrCodeGenerationRsp;
    }

    @Override
    public MerchantInvalidQRCodeRsp invalidQRCode(Integer merchantId) {
        String QRCODE_URL = "http://wechat.cheyifu2016.com:8080/wexin/login.action?uuid=";
        MerchantInvalidQRCodeRsp merchantInvalidQRCodeRsp = new MerchantInvalidQRCodeRsp();
        merchantInvalidQRCodeRsp.setResult(MerchantBusinessRsp.FAIL);
        try {
            String uuid = UUID.randomUUID().toString();
            merchantInfoMapper.updateQRCode(merchantId, uuid);
            merchantInvalidQRCodeRsp.setStrError("二维码刷新成功！");
            merchantInvalidQRCodeRsp.setQrcodeUrl(QRCODE_URL + uuid);
            merchantInvalidQRCodeRsp.setResult(MerchantBusinessRsp.SUCCESS);
        } catch (Exception e) {
            logger.error("作废二维码失败！{}", e.getMessage());
            merchantInvalidQRCodeRsp.setStrError("服务器忙，请稍后重试！");
            return merchantInvalidQRCodeRsp;
        }
        return merchantInvalidQRCodeRsp;
    }


    private MerchantLoginItem getMerchantInfo(MerchantInfo merchantInfo) {
        Parking parking = parkingMapper.getParkingById(merchantInfo.getParkingId());
        LocalAdminpara localAdminpara = localAdminparaMapper.getByParkingIdAndParaKey(merchantInfo.getParkingId(),
                LocalAdminpara.USE_COUPON);
        //获取优惠券绑定的计费规则
        FeeGroup feeGroup = feeGroupMapper.getByLocalFeegroupIdAndParkingId(merchantInfo.getFeeGroupId(), parking.getId());
        if (feeGroup == null) {
            return null;
        }
        MerchantLoginItem item = new MerchantLoginItem();
        if (parking != null && localAdminpara != null && StringUtils.isNotEmpty(localAdminpara.getParaValue())
                && Integer.parseInt(localAdminpara.getParaValue()) == Parking.ENABLE_COUPON) {
            item.setParkingId(parking.getId());
            item.setParkingName(parking.getName());
            item.setMerchantId(merchantInfo.getId());
            item.setLocalMerchantId(merchantInfo.getLocalMerchantInfoId());
            if (feeGroup.getFreeHours() != null) {
                item.setFreeHours(feeGroup.getFreeHours());
            }
            if (feeGroup.getFreeAmount() != null) {
                item.setFreeAmount(feeGroup.getFreeAmount());
            }
            if (merchantInfo.getMerchantType() != null
                    && merchantInfo.getMerchantType() == MerchantInfo.MERCHANT_TYPE_ALL_COUPON_TIME) {
                item.setRemainAllHours(merchantInfo.getRemainAllHours());
            } else {
                item.setRemainAllHours(0);
            }

            if (merchantInfo.getMerchantType() != null && merchantInfo.getMerchantType() == MerchantInfo.MERCHANT_TYPE_ALL_COUPON_AMOUNT) {
                item.setBalance(merchantInfo.getBalance());
            } else {
                item.setBalance(0);
            }
            item.setMerchantType(merchantInfo.getMerchantType() == null ? 1 : merchantInfo.getMerchantType());
            item.setMerchantFeegroupType(feeGroup.getUseWay() == 2 ? MerchantLoginItem.ONLINE_COUPONS : MerchantLoginItem.OFFLINE_COUPONS);
        }
        return item;
    }
}
